<template>
  <view class="order-page">
    <!-- 订单标签切换 -->
    <view class="order-tabs">
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'current' }"
        @click="switchTab('current')"
      >
        <text class="tab-text">当前订单</text>
        <view v-if="orderStore.activeOrders.length > 0" class="tab-badge">
          {{ orderStore.activeOrders.length }}
        </view>
      </view>
      <view 
        class="tab-item" 
        :class="{ active: activeTab === 'history' }"
        @click="switchTab('history')"
      >
        <text class="tab-text">历史订单</text>
      </view>
    </view>
    
    <!-- 订单列表 -->
    <scroll-view 
      class="order-list" 
      scroll-y 
      refresher-enabled 
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 当前订单 -->
      <view v-if="activeTab === 'current'">
        <view v-if="orderStore.activeOrders.length === 0" class="empty-state">
          <view class="empty-icon">📋</view>
          <text class="empty-title">暂无当前订单</text>
          <text class="empty-desc">快去预约座位开始游戏吧</text>
          <button class="empty-btn" @click="goToSeatSelection">
            立即预约
          </button>
        </view>
        
        <view v-else>
          <view 
            v-for="order in orderStore.activeOrders" 
            :key="order.id"
            class="order-item"
            @click="goToOrderDetail(order.id)"
          >
            <view class="order-header">
              <text class="order-number">订单号: {{ order.id }}</text>
              <view class="order-status" :class="getStatusClass(order.status)">
                {{ getStatusText(order.status) }}
              </view>
            </view>
            
            <view class="order-content">
              <view class="seat-info">
                <text class="seat-number">{{ order.seatNumber }}</text>
                <text class="seat-time">{{ formatOrderTime(order) }}</text>
              </view>
              
              <view v-if="order.status === 'in_progress'" class="remaining-time">
                <text class="time-label">剩余时间</text>
                <text class="time-value">{{ getRemainingTime(order) }}</text>
              </view>
            </view>
            
            <view class="order-footer">
              <text class="order-amount">¥{{ order.totalAmount.toFixed(2) }}</text>
              <view class="order-actions">
                <button 
                  v-if="order.status === 'pending'" 
                  class="btn btn-secondary btn-small"
                  @click.stop="cancelOrder(order.id)"
                >
                  取消
                </button>
                <button 
                  v-if="order.status === 'in_progress'" 
                  class="btn btn-secondary btn-small"
                  @click.stop="extendOrder(order.id)"
                >
                  续费
                </button>
                <button 
                  v-if="order.status === 'in_progress'" 
                  class="btn btn-primary btn-small"
                  @click.stop="endOrder(order.id)"
                >
                  结束
                </button>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 历史订单 -->
      <view v-else>
        <view v-if="orderStore.historyOrders.length === 0" class="empty-state">
          <view class="empty-icon">📜</view>
          <text class="empty-title">暂无历史订单</text>
          <text class="empty-desc">您的订单记录将在这里显示</text>
        </view>
        
        <view v-else>
          <view 
            v-for="order in orderStore.historyOrders" 
            :key="order.id"
            class="order-item"
            @click="goToOrderDetail(order.id)"
          >
            <view class="order-header">
              <text class="order-number">订单号: {{ order.id }}</text>
              <view class="order-status" :class="getStatusClass(order.status)">
                {{ getStatusText(order.status) }}
              </view>
            </view>
            
            <view class="order-content">
              <view class="seat-info">
                <text class="seat-number">{{ order.seatNumber }}</text>
                <text class="seat-time">{{ formatOrderTime(order) }}</text>
              </view>
              
              <view class="order-duration">
                <text class="duration-text">使用时长: {{ order.duration }}小时</text>
              </view>
            </view>
            
            <view class="order-footer">
              <text class="order-amount">¥{{ order.totalAmount.toFixed(2) }}</text>
              <view class="order-actions">
                <button 
                  v-if="order.status === 'completed'" 
                  class="btn btn-secondary btn-small"
                  @click.stop="rateOrder(order.id)"
                >
                  评价
                </button>
                <button 
                  class="btn btn-primary btn-small"
                  @click.stop="rebookOrder(order)"
                >
                  再次预约
                </button>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 底部间距 -->
      <view class="bottom-spacing"></view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useOrderStore } from '@/stores/order'
import { useUserStore } from '@/stores/user'
import { useSeatStore } from '@/stores/seat'
import { formatTime, showError, showSuccess, showConfirm } from '@/utils/common'

const orderStore = useOrderStore()
const userStore = useUserStore()
const seatStore = useSeatStore()

// 响应式数据
const activeTab = ref('current')
const refreshing = ref(false)

// 方法
const switchTab = (tab) => {
  activeTab.value = tab
}

const onRefresh = async () => {
  refreshing.value = true
  try {
    await orderStore.fetchOrders()
    showSuccess('刷新成功')
  } catch (error) {
    showError('刷新失败')
  } finally {
    refreshing.value = false
  }
}

const getStatusClass = (status) => {
  const statusMap = {
    pending: 'status-pending',
    confirmed: 'status-confirmed',
    in_progress: 'status-progress',
    completed: 'status-completed',
    cancelled: 'status-cancelled'
  }
  return statusMap[status] || ''
}

const getStatusText = (status) => {
  const statusMap = {
    pending: '待确认',
    confirmed: '已确认',
    in_progress: '使用中',
    completed: '已完成',
    cancelled: '已取消'
  }
  return statusMap[status] || '未知'
}

const formatOrderTime = (order) => {
  const start = formatTime(order.startTime, 'MM-DD HH:mm')
  const end = formatTime(order.endTime, 'HH:mm')
  return `${start} - ${end}`
}

const getRemainingTime = (order) => {
  const seconds = orderStore.getRemainingTime(order)
  return orderStore.formatRemainingTime(seconds)
}

const goToOrderDetail = (orderId) => {
  uni.navigateTo({
    url: `/pages/order/detail?id=${orderId}`
  })
}

const goToSeatSelection = () => {
  uni.switchTab({
    url: '/pages/seat/seat'
  })
}

const cancelOrder = async (orderId) => {
  const confirmed = await showConfirm('确定要取消这个订单吗？')
  if (confirmed) {
    const result = await orderStore.cancelOrder(orderId)
    if (result.success) {
      showSuccess('订单已取消')
    } else {
      showError(result.message || '取消失败')
    }
  }
}

const extendOrder = (orderId) => {
  uni.showModal({
    title: '续费功能',
    content: '续费功能正在开发中...',
    showCancel: false
  })
}

const endOrder = async (orderId) => {
  const confirmed = await showConfirm('确定要结束当前订单吗？')
  if (confirmed) {
    const result = await orderStore.completeOrder(orderId)
    if (result.success) {
      showSuccess('订单已结束')
    } else {
      showError(result.message || '结束失败')
    }
  }
}

const rateOrder = (orderId) => {
  uni.showModal({
    title: '评价功能',
    content: '评价功能正在开发中...',
    showCancel: false
  })
}

const rebookOrder = (order) => {
  // 选择相同座位
  const success = seatStore.selectSeat(order.seatId)
  if (success) {
    uni.navigateTo({
      url: '/pages/booking/booking'
    })
  } else {
    showError('该座位当前不可用')
  }
}

// 生命周期
onMounted(() => {
  // 检查登录状态
  if (!userStore.isLoggedIn) {
    uni.showModal({
      title: '请先登录',
      content: '查看订单需要先登录账户',
      confirmText: '去登录',
      success: (res) => {
        if (res.confirm) {
          uni.navigateTo({
            url: '/pages/login/login'
          })
        } else {
          uni.switchTab({
            url: '/pages/index/index'
          })
        }
      }
    })
    return
  }
  
  // 初始化订单数据
  if (orderStore.orders.length === 0) {
    orderStore.initMockOrders()
  }
})
</script>

<style lang="scss" scoped>
.order-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: var(--color-background);
}

// 订单标签
.order-tabs {
  background: white;
  display: flex;
  border-bottom: 1px solid var(--color-border);
  box-shadow: var(--shadow-sm);
}

.tab-item {
  flex: 1;
  position: relative;
  padding: 16px;
  text-align: center;
  transition: all var(--transition-normal);

  &.active {
    color: var(--color-primary);

    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 50%;
      transform: translateX(-50%);
      width: 30px;
      height: 3px;
      background: var(--color-primary);
      border-radius: 2px;
    }
  }

  &:active {
    background: var(--color-background);
  }
}

.tab-text {
  font-size: 16px;
  font-weight: 500;
  color: var(--color-text-primary);
}

.tab-badge {
  position: absolute;
  top: 8px;
  right: 20px;
  background: var(--color-error);
  color: white;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 8px;
  min-width: 16px;
  text-align: center;
}

// 订单列表
.order-list {
  flex: 1;
  padding: 16px;
}

.order-item {
  background: white;
  border-radius: var(--radius-xl);
  padding: 20px;
  margin-bottom: 16px;
  box-shadow: var(--shadow-sm);
  transition: all var(--transition-normal);

  &:active {
    transform: scale(0.98);
  }
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.order-number {
  font-size: 14px;
  color: var(--color-text-secondary);
}

.order-status {
  padding: 4px 12px;
  border-radius: var(--radius-md);
  font-size: 12px;
  font-weight: 500;

  &.status-pending {
    background: rgba(255, 149, 0, 0.1);
    color: var(--color-warning);
  }

  &.status-confirmed {
    background: rgba(0, 122, 255, 0.1);
    color: var(--color-primary);
  }

  &.status-progress {
    background: rgba(52, 199, 89, 0.1);
    color: var(--color-success);
  }

  &.status-completed {
    background: rgba(142, 142, 147, 0.1);
    color: var(--color-text-secondary);
  }

  &.status-cancelled {
    background: rgba(255, 59, 48, 0.1);
    color: var(--color-error);
  }
}

.order-content {
  margin-bottom: 16px;
}

.seat-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.seat-number {
  font-size: 24px;
  font-weight: bold;
  color: var(--color-text-primary);
}

.seat-time {
  font-size: 14px;
  color: var(--color-text-secondary);
}

.remaining-time {
  background: rgba(52, 199, 89, 0.1);
  border-radius: var(--radius-lg);
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.time-label {
  font-size: 14px;
  color: var(--color-success);
}

.time-value {
  font-size: 18px;
  font-weight: bold;
  color: var(--color-success);
}

.order-duration {
  .duration-text {
    font-size: 14px;
    color: var(--color-text-secondary);
  }
}

.order-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-amount {
  font-size: 20px;
  font-weight: bold;
  color: var(--color-primary);
}

.order-actions {
  display: flex;
  gap: 8px;
}

// 按钮样式
.btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 8px 16px;
  border: none;
  border-radius: var(--radius-md);
  font-size: 14px;
  font-weight: 500;
  text-align: center;
  cursor: pointer;
  transition: all var(--transition-normal);

  &:active {
    transform: scale(0.95);
  }

  &.btn-primary {
    background: var(--color-primary);
    color: white;
  }

  &.btn-secondary {
    background: transparent;
    color: var(--color-text-secondary);
    border: 1px solid var(--color-border);
  }

  &.btn-small {
    padding: 6px 12px;
    font-size: 12px;
  }
}

// 空状态
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.empty-icon {
  font-size: 64px;
  color: var(--color-text-tertiary);
  margin-bottom: 16px;
}

.empty-title {
  font-size: 18px;
  font-weight: 600;
  color: var(--color-text-primary);
  margin-bottom: 8px;
}

.empty-desc {
  font-size: 14px;
  color: var(--color-text-secondary);
  margin-bottom: 24px;
  line-height: 1.5;
}

.empty-btn {
  background: var(--color-primary);
  color: white;
  border: none;
  border-radius: var(--radius-lg);
  padding: 12px 24px;
  font-size: 16px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(0, 122, 255, 0.3);
  transition: all var(--transition-normal);

  &:active {
    transform: scale(0.95);
  }
}

.bottom-spacing {
  height: 20px;
}

// 响应式适配
@media (max-width: 375px) {
  .order-list {
    padding: 12px;
  }

  .order-item {
    padding: 16px;
  }

  .seat-number {
    font-size: 20px;
  }

  .order-amount {
    font-size: 18px;
  }

  .order-actions {
    flex-direction: column;
    gap: 6px;

    .btn {
      width: 100%;
    }
  }
}
</style>
